package com.cangshi.mail;

import com.cangshi.entity.JSONException;
import com.sun.mail.util.MailSSLSocketFactory;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.security.GeneralSecurityException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Random;

/**
 * Created by Eoly on 2017/4/8.
 */
public class MailManage {

    private static Map<String, MailEntity> mailEntityMap = new HashMap<String, MailEntity>();

    private static String serverEmailAddress = "cangshi520@qq.com";

    private static String serverEmailCode = "atmomofgyxiwbjei";

    public static String getServerEmailCode() {
        return serverEmailCode;
    }

    public static void setServerEmailCode(String serverEmailCode) {
        MailManage.serverEmailCode = serverEmailCode;
    }

    public static String getServerEmailAddress() {
        return serverEmailAddress;
    }

    public static void setServerEmailAddress(String serverEmailAddress) {
        MailManage.serverEmailAddress = serverEmailAddress;
    }

    public static Map<String, MailEntity> getMailEntityMap() {
        return mailEntityMap;
    }

    public static void setMailEntityMap(Map<String, MailEntity> mailEntityMap) {
        MailManage.mailEntityMap = mailEntityMap;
    }

    public static void addMail(MailEntity entity) {
        mailEntityMap.put(entity.getMailAddress(), entity);
    }

    public static MailEntity addMail(String mailAddress) {

        MailEntity mailEntity = new MailEntity(mailAddress);

        mailEntityMap.put(mailAddress, mailEntity);

        return mailEntity;
    }

    public static void removeMail(String mailAddress) {
        mailEntityMap.remove(mailAddress);
    }

    public static void removeAll() {
        mailEntityMap.clear();
    }

    public static MailEntity getMail(String mailAddress){
        return mailEntityMap.get(mailAddress);
    }

    public static class MailEntity {
        private String mailAddress;
        private String mailCheckString;

        public MailEntity(String mailAddress) {
            this();
            this.mailAddress = mailAddress;
        }

        public MailEntity() {
            buildCheckString();
        }

        public String getMailAddress() {
            return mailAddress;
        }

        public void setMailAddress(String mailAddress) {
            this.mailAddress = mailAddress;
        }

        public String getMailCheckString() {
            return mailCheckString;
        }

        public void setMailCheckString(String mailCheckString) {
            this.mailCheckString = mailCheckString;
        }

        private void buildCheckString() {
            StringBuilder stringBuilder = new StringBuilder();

            for (int i = 0; i < 7; i++) {
                stringBuilder.append(new Random().nextInt(10));
            }

            this.mailCheckString = stringBuilder.toString();
        }

        public void newThreadToSentEmailForCheck() {
            final MailEntity entity = this;

            new Thread(new Runnable() {
                public void run() {
                    try {
                        entity.sendEmail(serverEmailAddress,serverEmailCode);
                    } catch (GeneralSecurityException e) {
                        throw new JSONException(301, e.getMessage());
                    } catch (MessagingException e) {
                        throw new JSONException(302, e.getMessage());
                    }
                }
            }).start();
        }

        private void sendEmail(final String serverEmailAddress, final String serverEmailCode) throws GeneralSecurityException, MessagingException {
            Properties props = new Properties();
            props.setProperty("mail.host", "smtp.qq.com");
            props.setProperty("mail.smtp.auth", "true");

            //QQ邮箱的SSL加密。
            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            props.put("mail.smtp.ssl.enable", "true");
            props.put("mail.smtp.ssl.socketFactory", sf);

            //authenticator参数，登录自己的邮箱帐号密码，
            Authenticator authenticator = new Authenticator() {
                /**
                 * 注意，QQ邮箱的规则是如果不是由腾讯的网页或者客户端打开登录的话，在其他任何地方
                 *登录邮箱，密码必须使用授权码，授权码下面会讲解，vlyvawibbsribgee
                 *xxxxxxx:自己的QQ邮箱登录帐号，也就是qq号
                 *yyyyyyy:密码，使用授权码登录，而不能使用原始的QQ密码
                 */
                @Override
                public PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(serverEmailAddress, serverEmailCode);
                }
            };

            Session session = Session.getDefaultInstance(props, authenticator);

            //2、发送的内容对象Message
            Message message = new MimeMessage(session);
            //2.1、发件人是谁
            message.setFrom(new InternetAddress(serverEmailAddress));
            // 2.2  , to:收件人 ; cc:抄送 ; bcc :暗送.
            /**
             * 收件人是谁？
             *         第一个参数：
             *             RecipientType.TO    代表收件人
             *             RecipientType.CC    抄送
             *             RecipientType.BCC    暗送
             *         比如A要给B发邮件，但是A觉得有必要给要让C也看看其内容，就在给B发邮件时，
             *         将邮件内容抄送给C，那么C也能看到其内容了，但是B也能知道A给C抄送过该封邮件
             *         而如果是暗送(密送)给C的话，那么B就不知道A给C发送过该封邮件。
             *     第二个参数
             *         收件人的地址，或者是一个Address[]，用来装抄送或者暗送人的名单。或者用来群发。
             */
            message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(this.mailAddress));
            // 2.3 主题（标题）
            message.setSubject("注册随手帮帐号");
            // 2.4 正文
            String str = "您的验证码是：" + this.mailCheckString;
            message.setContent(str, "text/html;charset=UTF-8");
            //3、发送
            Transport.send(message);
        }


    }
}
